<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/16
 * 描述:
 */

namespace app\result;

use app\model\goods\Goods;
use app\model\goods\GoodsCollect;
use app\model\goods\GoodsComment;
use app\model\goods\GoodsSpecPrice;
use app\model\user\User;
use app\result\goods\GoodsActionResult;
use app\result\goods\GoodsCommentResult;

class GoodsResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Goods();
    }

    /** 推荐商品列表
     * @param $args
     * @return array
     */
    public function api_recommend_list($args = [])
    {
        //(new GoodsActionResult())->test();
        $style = [
            'background' => '#f3f3f3',
            'display' => 'list',//list/slide
            'column' => '2',
            'show' => [
                'goodsName' => '1',
                'goodsPrice' => '1',
                'linePrice' => '1'
            ]
        ];

        //首页推荐 todo
        $where = [['is_on_sale', '=', 1], ['is_recommend', '=', 1]];
        $data_list = $this->model->data_list($where, 'goods_id as item_id,goods_name as name,goods_image as image,goods_price', 'goods_id desc', 1, 4);
        return [
            'style' => $style,
            'data_list' => $data_list,
        ];
    }

    public function api_list($args = [], $user_id = 0): array
    {
        $page = intval($args['page'] ?? 1);
        $limit = intval($args['limit'] ?? 20);
        $keywords = $args['keywords'] ?? '';
        $category_id = intval($args['category_id'] ?? 0);
        $order_by = trim($args['order_by'] ?? '');
        $where = [['is_on_sale', '=', 1]];
        if ($keywords) {
            $where[] = ['goods_name', 'like', '%' . $keywords . '%'];
        }
        if ($category_id) {
            $where[] = ['category_id', '=', $category_id];
        }
        $order = 'click_count desc, sales_num desc, goods_id desc';
        if ($order_by === 'sales_desc') {
            $order = 'sales_num desc';
        } elseif ($order_by === 'sales_asc') {
            $order = 'sales_num asc';
        } elseif ($order_by === 'price_desc') {
            $order = 'goods_price desc';
        } elseif ($order_by === 'price_asc') {
            $order = 'goods_price asc';
        }
        $field = 'goods_id as item_id,goods_price,goods_name as name,goods_image as image,market_price,sales_num,shipping_fee,goods_type';
        $data = $this->model->data_list($where, $field, $order, $page, $limit)?->toArray();
        if ($data) {
            $myCollect = (new GoodsCollect())->data_list_nopage(['goods_id' => array_column($data, 'item_id'), 'user_id' => $user_id], 'goods_id');
            if ($myCollect) {
                $myCollect = array_column($myCollect, null, 'goods_id');
            }
            foreach ($data as &$v) {
                $v['is_collect'] = isset($myCollect[$v['item_id']]) ? 1 : 0;
                $v['tags'] = self::get_tags($v);
            }
            unset($v);
        }
        $lazyLoadConfig = [
            'duration' => 300,//触发加载的延迟时间，单位 ms（默认300）
            'threshold' => -300,//触发加载时的位置，见上方说明，单位 rpx（默认300）
        ];
        return self::success_return('success', [
            'lazyLoadConfig' => $lazyLoadConfig,
            'list' => $data
        ]);
    }

    public static function get_tags($goods): array
    {
        $tags = [];
        if (empty($goods['shipping_fee'])) {
            $tags[] = ['text' => '包邮', 'type' => 'success'];
        }
        if ($goods['goods_type'] === 2) {
            $tags[] = ['text' => '虚拟', 'type' => 'warning'];
        } else {
            $tags[] = ['text' => '实物', 'type' => 'primary'];
        }
        if ($goods['sales_num'] > 5) {
            $tags[] = ['text' => '热销', 'type' => 'error'];
        }
        return $tags;
    }

    public function api_detail($user_id, $args = []): array
    {
        $item_id = trim($args['item_id'] ?? 0);
        if (!$item_id) {
            return self::error_return('请选择商品');
        }
        $goods = $this->model->data_get(['goods_id' => $item_id]);
        if (!$goods) {
            return self::error_return('商品不存在');
        }
        if ($goods['is_on_sale'] !== 1) {
            return self::error_return('商品已下架');
        }
        $goods = $goods->toArray();
        $goods['goods_content'] = htmlspecialchars_decode($goods['goods_content']);
        $goods['images'] = array_filter(explode(',', $goods['goods_image_list']));
        if (!$goods['images']) {
            $goods['images'] = [
                $goods['goods_image']
            ];
        }
        $goods['sales_num'] = $goods['sales_fake'] + $goods['sales_num'];
        $goods['spec_list'] = (new GoodsSpecPrice())->data_list_nopage(['goods_id' => $item_id]);

        $cart_total_num = CartResult::current_cart_num($user_id);//购物车数量
        $goods['comment_count'] = (new GoodsComment())->data_count(['goods_id' => $item_id]);//评论数量
        if ($goods['comment_count'] > 0) {
            $commentList = (new GoodsComment())->data_list(['goods_id' => $item_id], '*', 'comment_id desc', 1, 3);
            if ($commentList) {
                $commentList = $commentList->toArray();
                $commentList = (new GoodsCommentResult())->format_data($commentList);
            }
        }
        $kefuInfo = '&kefu_id=10000';//todo 客服信息动态化
        $enableShare = false;//todo 动态化配置

        $goods['comment_list'] = $commentList ?? [];
        unset($goods['virtual_info']);
        $service = $goods['service'] ? @json_decode($goods['service'], true) : [];
        $goods['service'] = [];
        if (!empty($service)) {
            //'7天无理由退换货', '48小时发货', '退货包运费'
            if (in_array('7天无理由退换货', $service)) {
                $goods['service'][] = [
                    'name' => '7天无理由退换货',
                    'desc' => '如果在7天内，您对商品有质量问题，可申请退'
                ];
            }
            if (in_array('48小时发货', $service)) {
                $goods['service'][] = [
                    'name' => '48小时发货',
                    'desc' => '订单支付后，48小时内发货'
                ];
            }
            if (in_array('退货包运费', $service)) {
                $goods['service'][] = [
                    'name' => '退货包运费',
                    'desc' => '退货时，卖家承担运费'
                ];
            }
        }
        //增加访问量
        $this->model->data_update(['goods_id' => $item_id], ['click_count' => ['inc', 1]]);

        return self::success_return('success', [
            'cart_total_num' => $cart_total_num,
            'kefu_num' => 0,
            'kefu_info' => $kefuInfo,
            'info' => $goods,
            'enable_share' => $enableShare,
        ]);
    }


}
